﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OA.Manager;
using OA.Model;
using OA.Utility;
using System.Data;

namespace OA.Bll.Reimbursement
{
    public class ReimbursementPresenter : IBll
    {
        private readonly ReimbursementManager _manager;
        public ReimbursementPresenter()
        {
            _manager = new ReimbursementManager();
        }

        public string Get(JsonReq req)
        {
            int reimbursementId = Convert.ToInt32(req.Options["ReimbursementId"]);
            ReimbursementInfoView model = _manager.GetReimbursementInfoViewByID(reimbursementId);
            return JsonHelper.JsonSerializer<ReimbursementInfoView>(model);
        }

        public string GetSearchAll(JsonReq req)
        {
            return "";
        }

        public string Paged(JsonReq req)
        {
            ReimbursementInfoView reimbursement = JsonHelper.JsonDeserialize<ReimbursementInfoView>(req.Options);
            int pageIndex = Convert.ToInt32(req["page"]);
            int pageSize = Convert.ToInt32(req["rows"]);
            int total = 0;
            DataTable dt = _manager.ReimbursementPagedView(reimbursement, pageIndex, pageSize);
            return JsonHelper.OnDataGrid(dt, total);
        }

        public string Search(JsonReq req)
        {
            int pageIndex = Convert.ToInt32(req["page"]);
            int pageSize = Convert.ToInt32(req["rows"]);
            int total = 0;
            StringBuilder sb = new StringBuilder();
            if (req.Options.ContainsKey("CostSubject") && !string.IsNullOrEmpty(req["CostSubject"]))
            {
                string costSubject = req["CostSubject"];
                if (costSubject == "机票报销单")
                    sb.Append(" and Id in (select ReimbursementId from ReimbursementBusinessTravel rbt where rbt.ReimbursementId=rv.Id )");
                else if (costSubject == "出差补助")
                    sb.Append(" and Id in (select ReimbursementId from ReimbursementPlaneTicket rbt where rbt.ReimbursementId= rv.Id)");
                else
                {
                    costSubject = costSubject.Split(' ')[0];
                    sb.Append("and Id in (select ReimbursementId from ReimbursementItem ri where ri.ReimbursementId= rv. Id and ri.CostItemNo='" + costSubject + "' )");
                }
                req.Options.Remove("CostSubject");
            }
            if (req.Options.ContainsKey("Monthly") && !string.IsNullOrEmpty(req["Monthly"]))
            {
                sb.Append(" and month(rv.ReimbursementTime)=" + req["Monthly"] + "");
                req.Options.Remove("Monthly");
            }
            if (req.Options.ContainsKey("Quarter") && !string.IsNullOrEmpty(req["Quarter"]))
            {
                int quarter = Convert.ToInt32(req["Quarter"]);
                sb.Append(" and  month(rv.ReimbursementTime)>" + (quarter - 1) * 3 + " and month(rv.ReimbursementTime)<=" + quarter * 3);
                req.Options.Remove("Quarter");
            }
            if (req.Options.ContainsKey("Year") && !string.IsNullOrEmpty(req["Year"]))
            {
                sb.Append(" and yaer(rv.ReimbursementTime)=" + req["Year"]);
                req.Options.Remove("Year");
            }
            if (req.Options.ContainsKey("AmountMin") && req.Options.ContainsKey("AmountMax") && !string.IsNullOrEmpty(req["AmountMin"]) && !string.IsNullOrEmpty(req["AmountMax"]))
            {
                sb.Append(" and rv.TotalMoney>=" + req["AmountMin"] + " and rv.TotalMoney<=" + req["AmountMax"]);
                req.Options.Remove("AmountMin");
                req.Options.Remove("AmountMax");
            }
            //T info = JsonHelper.JsonDeserialize<T>(req.Options);
            string sql = JsonHelper.GetQueryFilterString(req.Options, false);
            sb.Append(sql);
            Type type = typeof(ReimbursementInfoView);
            if (type.GetProperties().Count(a => a.Name.ToLower() == "createtime") > 0)
                sb.Append(" order by [createtime] desc");
            DataTable dt = new ManagerParent<ReimbursementInfoView>().GetSearchPaged("ReimbursementView rv", "", sb.ToString(), pageIndex, pageSize, ref total);
            return JsonHelper.OnDataGrid(dt, total);
        }

        public string Add(JsonReq req)
        {
            #region 增加报销内容信息
            ReimbursementInfo info = JsonHelper.JsonDeserialize<ReimbursementInfo>(req.Options);
            int id = _manager.InsertReimbursementInfo(info);
            #endregion
            bool bl = false;
            #region 增加报销详情
            ReimbursementItemInfo reimbursementItem;
            foreach (Dictionary<string, string> dictionary in req.ArrayOptions)
            {
                if (!dictionary.ContainsKey("type"))
                {
                    reimbursementItem = JsonHelper.JsonDeserialize<ReimbursementItemInfo>(dictionary);
                    reimbursementItem.ReimbursementId = id;
                    bl = _manager.InsertReimbursementItemInfo(reimbursementItem);
                    if (!bl)
                        break;
                }
                else
                {
                    switch (dictionary["type"])
                    {
                        case "businesstrip":
                            {
                                #region 增加出差报销信息
                                ReimbursementBusinessTravelInfo reimbursementBusinessTravel = JsonHelper.JsonDeserialize<ReimbursementBusinessTravelInfo>(dictionary);
                                reimbursementBusinessTravel.ReimbursementId = id;
                                bl = _manager.InsertReimbursementBusinessTripInfo(reimbursementBusinessTravel);
                                #endregion
                            }
                            break;
                        case "PlaneTicket":
                            {
                                #region 增加机票报销信息
                                ReimbursementPlaneTicketInfo reimbursementPlaneTicket = JsonHelper.JsonDeserialize<ReimbursementPlaneTicketInfo>(dictionary);
                                reimbursementPlaneTicket.ReimbursementId = id;
                                bl = _manager.InsertReimbursementPlaneTicketInfo(reimbursementPlaneTicket);
                                #endregion
                            }
                            break;
                    }
                }
            }
            #endregion


            return JsonHelper.ResultToJson(bl, ExecuteType.Add);
        }
        /// <summary>
        /// 修改报销信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public string Update(JsonReq req)
        {
            ReimbursementInfo info = JsonHelper.JsonDeserialize<ReimbursementInfo>(req.Options);
            info.ReimbursementTime = info.ReimbursementTime ?? DateTime.Now;
            bool bl = false;
            {
                if (_manager.UpdateReimbursementInfo(info, null)) //报销内容信息
                {
                    #region 修改报销详情
                    ReimbursementItemInfo reimbursementItem;
                    //插入成功后,对于有多条数据的ReimbursementItemInfo,ReimbursementPlaneTicketInfo
                    //先以ReimbursementId为条件将符合的数据删除,然后重新插入,
                    //若以判断方式,多增加查询开销,难以判断删除数据
                    //而且修改改为删除重新插入的方式对数据修改不会有影响,虽然改变了默认自动增长id,但是无影响.        
                    bool delItem = false, delPlane = false;
                    foreach (Dictionary<string, string> dictionary in req.ArrayOptions)
                    {
                        if (!dictionary.ContainsKey("type"))
                        {
                            reimbursementItem = JsonHelper.JsonDeserialize<ReimbursementItemInfo>(dictionary);
                            reimbursementItem.ReimbursementId = info.Id;
                            if (!delItem)
                            {
                                bl = _manager.DeleteReimbursementItemInfo(reimbursementItem);
                                delItem = true;
                            }
                            bl = _manager.InsertReimbursementItemInfo(reimbursementItem);
                            if (!bl)
                                break;
                        }
                        else
                        {
                            switch (dictionary["type"])
                            {
                                case "businesstrip":
                                    {
                                        #region 增加出差报销信息

                                        ReimbursementBusinessTravelInfo reimbursementBusinessTravel =
                                            JsonHelper.JsonDeserialize<ReimbursementBusinessTravelInfo>(dictionary);
                                        reimbursementBusinessTravel.ReimbursementId = info.Id;
                                        if (string.IsNullOrEmpty(dictionary["Id"]))
                                        {
                                            bl = _manager.InsertReimbursementBusinessTripInfo(reimbursementBusinessTravel);
                                        }
                                        else
                                            //if (_manager.IsExistReimbursementInfo(reimbursementBusinessTravel))
                                            bl =
                                                _manager.UpdateReimbursementBusinessTripInfo(
                                                    reimbursementBusinessTravel, null);

                                        #endregion
                                    }
                                    break;
                                case "PlaneTicket":
                                    {
                                        #region 增加机票报销信息

                                        ReimbursementPlaneTicketInfo reimbursementPlaneTicket =
                                            JsonHelper.JsonDeserialize<ReimbursementPlaneTicketInfo>(dictionary);
                                        reimbursementPlaneTicket.ReimbursementId = info.Id;
                                        if (!delPlane)
                                        {
                                            bl = _manager.DeleteReimbursementPlaneTicketInfo(reimbursementPlaneTicket);
                                            delPlane = true;
                                        }
                                        _manager.InsertReimbursementPlaneTicketInfo(reimbursementPlaneTicket);
                                        //if (string.IsNullOrEmpty(dictionary["Id"]))
                                        //{
                                        //    _manager.InsertReimbursementPlaneTicketInfo(reimbursementPlaneTicket);
                                        //}
                                        //else
                                        //    if (_manager.IsExistReimbursementInfo(reimbursementPlaneTicket))
                                        //        bl = _manager.UpdateReimbursementPlaneTicketInfo(reimbursementPlaneTicket,
                                        //                                                         null);
                                        //    else

                                        //        bl = _manager.DeleteReimbursementPlaneTicketInfo(reimbursementPlaneTicket);
                                        #endregion
                                    }
                                    break;
                            }
                        }
                    }
                    #endregion
                }

            }
            return JsonHelper.ResultToJson(bl, ExecuteType.Update);
        }
        public string Delete(JsonReq req)
        {
            int id = req["Id"].ToInt32();
            bool bl = _manager.DeleteReimbursementPlaneTicketInfo(new ReimbursementPlaneTicketInfo { ReimbursementId = id });
            if (bl)
            {
                bl = _manager.DeleteReimbursementItemInfo(new ReimbursementItemInfo { ReimbursementId = id });
                if (bl)
                {
                    bl =
                        _manager.DeleteReimbursementBusinessTravelInfo(new ReimbursementBusinessTravelInfo { ReimbursementId = id });
                    if (bl)
                        bl =
                            _manager.DeleteReimbursementInfo(new ReimbursementInfo { Id = id });
                }
            }
            return JsonHelper.ResultToJson(bl, ExecuteType.Delete);
        }


        public string IsExit(JsonReq req)
        {
            throw new NotImplementedException();
        }
    }
}
